<?php
/**
 * @author leon
 *
 */
class User{
	const sqlTable = "esUser";
	const cookie = "esUserToken";
	public $arrData = array(nickname, street, housenumber, postal, city, country, preselection);
	private $database, $id;
	public function __construct($sessionToken){
		$this->arrData = array_flip($this->arrData);
		$this->database = new Database();
		$this->loadUserData($sessionToken);
	}
	public static function createTable(){
		$database = new Database;
		$arrFields = array("nickname", "password", "street", "housenumber", "postal", "city", "country", "preselection", "sessiontoken");
		$arrTypes = array("TINYTEXT", "TINYTEXT", "TINYTEXT", "INT", "INT", "TINYTEXT", "TINYTEXT", "INT", "TINYTEXT");
		$database->createTable(User::sqlTable, $arrFields, $arrTypes);
	}
	private function loadUserData($sessionToken){
		$sqlQuery = $this->database->query("
			SELECT * FROM ".User::sqlTable."
			WHERE sessiontoken = '".$this->database->connection->real_escape_string($sessionToken)."'
		");
		$sqlResult = $sqlQuery->fetch_assoc();
		$this->id = $sqlResult[id];
		while(list($key, $val) = each($this->arrData)){
			$this->arrData[$key] = $sqlResult[$key];
		}
	}
	public function updateData($sessionToken){
		$sqlSet = " SET "; 
		while(list($key, $val) = each($this->arrData)){
			$sqlSet .= "$key = '".$this->database->connection->real_escape_string($val)."', ";
		}
		$sqlSet = trim($sqlSet, ", ");
		$sqlQuery = $database->query("
			UPDATE ".User::sqlTable.$sqlSet."
			WHERE sessiontoken = '".$this->database->connection->real_escape_string($sessionToken)."'
		");
	}
	/*
	 * Only for comunication spec, not the best way..
	 */
	public function getId(){
		return $this->id;
	}
	public function getNickname(){
		return $this->arrData[nickname];
	}
	public function getStreet(){
		return $this->arrData[street];
	}
	public function getHouseNumber(){
		return $this->arrData[houseNumber];
	}
	public function getPostal(){
		return $this->arrData[postal];
	}
	public function getCity(){
		return $this->arrData[city];
	}
	public function getCountry(){
		return $this->arrData[country];
	}
	public function getPreselection(){
		return $this->arrData[preselection];
	}
	public function setNickname($nickname){
		$this->arrData[nickname];
	}
	public function setPassword($password){
		$this->arrData[password];
	}
	public function setStreet($street){
		$this->arrData[street];
	}
	public function setHouseNumber($houseNumber){
		$this->arrData[houseNumber];
	}
	public function setPostal($postal){
		$this->arrData[postal];
	}
	public function setCity($city){
		$this->arrData[city];
	}
	public function setCountry($country){
		$this->arrData[country];
	}
	public function setPreselection($preselection){
		$this->arrData[preselection];
	}
}